<template>
  <div ref="mapContainer" class="map-container"></div>
</template>

<script>
import { ref, onMounted, watch } from "vue";
import { Map, View } from "ol";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { OSM, Vector as VectorSource } from "ol/source";
import { Draw } from "ol/interaction";
import { Style, Icon, Fill, Stroke } from "ol/style";
import Point from "ol/geom/Point";
import Feature from "ol/Feature";
import { fromLonLat } from "ol/proj";
import { GeoJSON } from "ol/format"; // 导入 GeoJSON 格式类
import { fetchCityData, fetchCityBoundaryData } from "../utils/api"; // 引入 API 请求方法

export default {
  name: "MapView",
  props: {
    drawType: String, // 当前绘图类型
    markerType: String, // 当前标记类型
  },
  emits: ["updateDrawType", "updateMarkerType"], // 定义更新事件
  setup(props, { emit }) {
    const mapContainer = ref(null);
    const map = ref(null);
    const draw = ref(null);
    const vectorSource = ref(new VectorSource({ wrapX: false }));
    const vectorLayer = new VectorLayer({ source: vectorSource.value });

    const boundarySource = ref(new VectorSource({ wrapX: false }));
    const boundaryLayer = new VectorLayer({ source: boundarySource.value });

    // 初始化地图
    onMounted(async () => {
      const view = new View({
        center: fromLonLat([0, 0]), // 初始中心点
        zoom: 1,
      });

      map.value = new Map({
        target: mapContainer.value,
        layers: [
          new TileLayer({ source: new OSM() }),
          vectorLayer,
          boundaryLayer,
        ],
        view: view,
      });

      // 获取城市边界数据
      await fetchAndDisplayCityBoundary();

      // 添加地图点击事件（仅当 markerType 非空时添加标记）
      map.value.on("singleclick", (event) => {
        if (props.markerType) {
          addMarker(props.markerType, event.coordinate);
        }
      });

      // 初始化绘图工具
      addInteraction(props.drawType);
    });

    // 获取城市边界数据并显示在地图上
    const fetchAndDisplayCityBoundary = async () => {
      try {
        const { city } = await fetchCityData(); // 获取当前城市信息
        const cityData = await fetchCityBoundaryData(city); // 获取城市 GeoJSON 数据

        if (cityData) {
          const center = cityData.properties.center; // 中心点
          const geoJsonData = {
            type: "FeatureCollection",
            features: [cityData],
          };

          const geoJsonFormat = new GeoJSON();
          const features = geoJsonFormat.readFeatures(geoJsonData, {
            featureProjection: map.value.getView().getProjection(),
          });

          const boundaryStyle = new Style({
            stroke: new Stroke({ color: "#ff0000", width: 2 }),
            fill: new Fill({ color: "rgba(255, 0, 0, 0.3)" }),
          });

          features.forEach((feature) => feature.setStyle(boundaryStyle));
          boundarySource.value.addFeatures(features);

          if (center) {
            map.value.getView().animate({
              center: fromLonLat(center),
              zoom: 8,
              duration: 2000,
            });
          }
        } else {
          console.error("Invalid city data");
        }
      } catch (error) {
        console.error("Failed to fetch city data or boundaries:", error);
      }
    };

    // 添加绘图交互
    const addInteraction = (type) => {
      if (draw.value) {
        map.value.removeInteraction(draw.value);
      }

      if (type === "clear") {
        vectorSource.value.clear(); // 清空所有绘制内容
        return;
      }

      if (type === "Freehand") {
        draw.value = new Draw({
          source: vectorSource.value,
          type: "LineString",
          freehand: true,
        });
      } else if (type && type !== "None") {
        draw.value = new Draw({
          source: vectorSource.value,
          type,
        });
      }

      if (draw.value) {
        map.value.addInteraction(draw.value);
      }
    };

    // 添加标记
    const addMarker = (type, coordinates) => {
      const markerIcons = {
        parking: "/icons/tingchechang.png",
        charging: "/icons/qichexiangguan-chongdianzhan.png",
        bus: "/icons/busstop.png",
        exit: "/icons/churukou.png",
        default: "/icons/defaultMarker.png",
      };

      const iconUrl = markerIcons[type] || markerIcons.default;

      const iconStyle = new Style({
        image: new Icon({
          src: iconUrl,
          scale: 0.15,
        }),
      });

      const marker = new Feature({
        geometry: new Point(coordinates), // 标记坐标
      });
      marker.setStyle(iconStyle);

      vectorSource.value.addFeature(marker);
    };

    // 监听绘图类型的变化
    watch(
      () => props.drawType,
      (newType) => {
        if (newType) {
          emit("updateMarkerType", null); // 禁用标记功能
          addInteraction(newType);
        }
      }
    );

    // 监听标记类型的变化
    watch(
      () => props.markerType,
      (newType) => {
        if (newType) {
          emit("updateDrawType", null); // 禁用绘图功能
        }
      }
    );

    return {
      mapContainer,
    };
  },
};
</script>

<style>
.map-container {
  width: 100%;
  height: 100vh;
}
</style>
